//
//  MBPhotoSelectViewController.m
//  Meboo
//
//  Created by kyo on 2024/3/8.
//

#import "MBPhotoSelectViewController.h"
#import "KLDrawView.h"
#import "MBCustomNavView.h"
#import <Photos/Photos.h>
@interface MBPhotoSelectViewController ()
@property (nonatomic,strong) UIImageView * chosedHeadImageView;
@property (nonatomic,strong) KLDrawView * boardView;
@property (nonatomic,assign) CGRect headImageOldRect;
@property (nonatomic,strong) UIView *circle;

@end

static  CGFloat viewWeidth;
static  CGFloat viewHeight;
static  CGFloat height;
static  CGFloat newImageWeidth;
static  CGFloat newImageHeight;
static const CGFloat animationTime =  0.3f;
static const CGFloat maxScale = 3;
@implementation MBPhotoSelectViewController

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:YES];
    _oldImage = nil;
    _chosedHeadImageView = nil;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    viewWeidth = self.view.frame.size.width;
    viewHeight = self.view.frame.size.height;
    height = MBHeightScale(500);
    self.view.backgroundColor = HEXS(@"24263F");
//    _circle = [[UIView alloc] initWithFrame:CGRectMake((viewWeidth - height)/2, 0, height, height)];
//    [self.view addSubview:_circle];
    // 初始化图片
    [self P_initSubImage];
    // 初始化手势
    [self P_initGestureRecognizer];
    // 初始化遮罩
    [self P_addmaskView];
    // 初始化按钮
    [self P_initSubBttons];
}



#pragma mark - 初始化控件
- (void)P_initSubImage{
    
    UIImageView * chosedHeadImageView = [[UIImageView alloc]initWithImage:self.oldImage];
    self.chosedHeadImageView = chosedHeadImageView;
    [self.view addSubview:chosedHeadImageView];
    chosedHeadImageView.center = self.view.center;
    
    CGFloat weidthScale = chosedHeadImageView.image.size.width / viewWeidth;
    CGFloat heightScale = chosedHeadImageView.image.size.height / viewHeight;

    
    // 长宽按照比例显示
    if (weidthScale > heightScale) {
        newImageWeidth = viewWeidth;
        newImageHeight = viewWeidth / (chosedHeadImageView.image.size.width / chosedHeadImageView.image.size.height);
        
        if (newImageHeight <= height) {
            newImageHeight = height;
            newImageWeidth = newImageHeight / (chosedHeadImageView.image.size.height / chosedHeadImageView.image.size.width);
        }
    }else{
        newImageHeight = viewHeight;
        newImageWeidth = viewHeight / (chosedHeadImageView.image.size.height / chosedHeadImageView.image.size.width);
        
        if (newImageWeidth <= height) {
            newImageWeidth = height;
            newImageHeight = newImageWeidth / (chosedHeadImageView.image.size.width / chosedHeadImageView.image.size.height);
        }
    }
    chosedHeadImageView.bounds = CGRectMake(0, 0, newImageWeidth, newImageHeight);
    
    self.headImageOldRect = chosedHeadImageView.frame;
}

- (void)P_initGestureRecognizer{
    
    UIPinchGestureRecognizer * pich = [[UIPinchGestureRecognizer alloc]initWithTarget:self action:@selector(pichHeadImage:)];
    [self.view addGestureRecognizer:pich];
    
    UIPanGestureRecognizer * pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(panHeadImage:)];
    [self.view addGestureRecognizer:pan];
}

- (void)P_addmaskView{
    
    UIView * maskView = [[UIView alloc]init];
    maskView.backgroundColor = [UIColor blackColor];
    maskView.frame = self.view.bounds;
    [self.view addSubview:maskView];
    CAShapeLayer * maskLayer = [[CAShapeLayer alloc]init];
    
    // 遮罩
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathAddRect(path, nil, CGRectMake(0, 0, viewWeidth, (viewHeight - height)/2));
    CGPathAddRect(path, nil, CGRectMake(0, (viewHeight + height)/2, viewWeidth, (viewHeight - height)/2));
    maskLayer.path = path;
    maskView.layer.mask = maskLayer;
    
    // 框
    KLDrawView * boardView = [[KLDrawView alloc]initWithFrame:CGRectMake(0, (viewHeight - height)/2, viewWeidth, height)];
    self.boardView = boardView;
    boardView.type = DrawViewTypeThree;
    
    [self.view addSubview:boardView];
    

}

- (void)P_initSubBttons{

    
    UIButton * tureButton = [[UIButton alloc]init];
    tureButton.titleLabel.font = MBFontSizeScale(18);
    tureButton.backgroundColor = HEXS(@"8EBBFF");
    tureButton.layer.cornerRadius = MBHeightScale(30);
    [self.view addSubview:tureButton];
    [tureButton setTitleColor:HEXS(@"24263F") forState:UIControlStateNormal];
    [tureButton setTitle:@"Save" forState:UIControlStateNormal];
    [tureButton addTarget:self action:@selector(P_clickTrueButton) forControlEvents:UIControlEventTouchUpInside];
    [tureButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(MBWidthScale(-32));
        make.bottom.mas_equalTo(-MBHeightScale(43)-TabbarSafeBottomMargin);
        make.width.mas_equalTo(MBWidthScale(118));
        make.height.mas_equalTo(MBHeightScale(60));
    }];
    
    MBCustomNavView * navView = [[MBCustomNavView alloc]init];
    [self.view addSubview:navView];
    [navView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(self.view);
        make.height.mas_equalTo(StatusBarAndNavigationBarHeight);
    }];
    
    UIButton * topSaveButton = [[UIButton alloc]init];
    [navView addSubview:topSaveButton];
    [topSaveButton setImage:ImageWithName(@"mine_save_photo") forState:0];
    [topSaveButton addTarget:self action:@selector(P_clickTrueButton) forControlEvents:UIControlEventTouchUpInside];
    [topSaveButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(MBWidthScale(-12));
        make.centerY.equalTo(navView.titleLab);
        make.width.height.mas_equalTo(MBHeightScale(24));
    }];
}


#pragma mark - 事件处理
// 缩放手势
- (void)pichHeadImage:(UIPinchGestureRecognizer *)pinch{
    
    if (pinch.state == UIGestureRecognizerStateBegan || pinch.state == UIGestureRecognizerStateChanged) {
        CGFloat newWidth = self.chosedHeadImageView.frame.size.width * pinch.scale;
        CGFloat newHeight = self.chosedHeadImageView.frame.size.height * pinch.scale;
        self.chosedHeadImageView.bounds = CGRectMake(0, 0, newWidth, newHeight);
        pinch.scale = 1;
    }else if(pinch.state == UIGestureRecognizerStateEnded){
        [self P_autoScale];
      
        [self P_autoTransLationUseRect:self.chosedHeadImageView.frame];
    }
}

//移动
- (void)panHeadImage:(UIPanGestureRecognizer *)pan{

    if (pan.state == UIGestureRecognizerStateBegan || pan.state == UIGestureRecognizerStateChanged) {
        
        CGPoint transLationPoint = [pan translationInView:self.view];
        CGFloat newCentX = self.chosedHeadImageView.center.x + transLationPoint.x;
        CGFloat newCentY = self.chosedHeadImageView.center.y + transLationPoint.y;
        self.chosedHeadImageView.center = CGPointMake(newCentX, newCentY);

        [pan setTranslation:CGPointZero inView:self.view.superview];
        
    }else if(pan.state == UIGestureRecognizerStateEnded){
        
        [self P_autoTransLationUseRect:self.chosedHeadImageView.frame];
    }
}

// 点击取消
- (void)P_clickCancleButton{
    self.chosedHeadImageView.frame = self.headImageOldRect;
    [self.currentViewController dismissViewControllerAnimated:YES completion:^{
    }];
    [self.navigationController popViewControllerAnimated:YES];
}

// 点击确定
- (void)P_clickTrueButton{
    __WeakSelf
    [self.circle addSubview:self.chosedHeadImageView];
    UIImage*tempImage = [self imageFromView:self.view rect:CGRectMake(MBWidthScale(18), (viewHeight-height)/2+MBHeightScale(22), viewWeidth-MBWidthScale(18*2), height-MBHeightScale(22*2))];
//    UIImage*tempImage = [self convertViewToImage:self.circle];
//    [self savePhoto:tempImage];
//    testViewController *test= [testViewController new];
//    test.oldImage = tempImage;
//    [self.navigationController pushViewController:test animated:YES];
        dispatch_async(dispatch_get_main_queue(), ^{
            // 不做这处理放大很多的情况下会有bug
            weakSelf.chosedHeadImageView.frame = weakSelf.headImageOldRect;


            if (weakSelf.ZHNheadImageBlock) {
                weakSelf.ZHNheadImageBlock(tempImage);
            }

            [weakSelf.navigationController popViewControllerAnimated:YES];
        });
}



// 移动处理
- (void)P_autoTransLationUseRect:(CGRect)choseHeadRect{
    CGFloat scale;
    if (self.chosedHeadImageView.frame.size.width >= viewWeidth) {
        scale = self.chosedHeadImageView.frame.size.height / viewHeight;
    }else{
        scale = self.chosedHeadImageView.frame.size.width / viewWeidth;
    }
    __WeakSelf
//    CGRect boardRect = self.boardView.frame;
    CGRect boardRect = CGRectMake(MBWidthScale(18), (viewHeight-height)/2+MBHeightScale(22), viewWeidth-MBWidthScale(18*2), height-MBHeightScale(22*2));
    
    CGFloat wid = (viewWeidth-self.chosedHeadImageView.frame.size.width)/2;
    CGFloat hei = (viewHeight-self.chosedHeadImageView.frame.size.height)/2;
    // 水平方向
    if (choseHeadRect.origin.x > boardRect.origin.x) {
        choseHeadRect.origin.x = boardRect.origin.x;
    }
    
    if (self.chosedHeadImageView.frame.size.width >= viewWeidth) {
        if (choseHeadRect.origin.x < wid *2 - boardRect.origin.x) {
            choseHeadRect.origin.x = wid *2 - boardRect.origin.x;
        }
    }else{
        choseHeadRect.origin.x = boardRect.origin.x;
    }

    // 垂直方向
    if (choseHeadRect.origin.y > boardRect.origin.y) {
        choseHeadRect.origin.y = boardRect.origin.y;
    }
    if (CGRectGetMaxY(choseHeadRect) <= CGRectGetMaxY(boardRect)) {
        choseHeadRect.origin.y = boardRect.origin.y + boardRect.size.height - choseHeadRect.size.height;
    }
    
//    if (self.chosedHeadImageView.frame.size.height >= viewHeight) {
//        if (choseHeadRect.origin.y < hei *2 - boardRect.origin.y) {
//            choseHeadRect.origin.y = hei *2 - boardRect.origin.y;
//        }
//    }else{
//        choseHeadRect.origin.y = boardRect.origin.y;
//    }
    
   
    if (choseHeadRect.size.width < boardRect.size.width || choseHeadRect.size.height < boardRect.size.height) {// 特殊情况
       
        [UIView animateWithDuration:animationTime animations:^{
            weakSelf.chosedHeadImageView.center = weakSelf.boardView.center;
        }];
        
    }else{
        
        [UIView animateWithDuration:animationTime animations:^{
            weakSelf.chosedHeadImageView.frame = choseHeadRect;
        }];
    }
    
}

// 缩放处理
- (void)P_autoScale{
    __WeakSelf
    CGFloat scale;
    if (self.chosedHeadImageView.frame.size.width >= viewWeidth) {
        scale = self.chosedHeadImageView.frame.size.height / viewHeight;
    }else{
        scale = self.chosedHeadImageView.frame.size.width / viewWeidth;
    }
    if (scale < 1) {
        [UIView animateWithDuration:animationTime animations:^{
            weakSelf.chosedHeadImageView.bounds = CGRectMake(0, 0,newImageWeidth, newImageHeight);
        }];
    }else if(scale > maxScale){
        
        [UIView animateWithDuration:animationTime animations:^{
            weakSelf.chosedHeadImageView.bounds = CGRectMake(0, 0,newImageWeidth * maxScale, newImageHeight * maxScale);
        }];
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

//view转图片
- (UIImage*)convertViewToImage:(UIView*)view{
    CGSize s = view.bounds.size;
    // 下面方法，第一个参数表示区域大小。第二个参数表示是否是非透明的。如果需要显示半透明效果，需要传NO，否则传YES。第三个参数就是屏幕密度了
    UIGraphicsBeginImageContextWithOptions(s, NO, [UIScreen mainScreen].scale);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage*image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

- (UIImage*)imageFromView:(UIView *)view rect:(CGRect)rect
{
    _boardView.hidden = YES;
    UIGraphicsBeginImageContextWithOptions(view.frame.size, NO, 1.0);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    CGRect myImageRect = rect;
    CGImageRef imageRef = image.CGImage;
    CGImageRef subImageRef = CGImageCreateWithImageInRect(imageRef,myImageRect );
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextDrawImage(context, myImageRect, subImageRef);
    UIImage* smallImage = [UIImage imageWithCGImage:subImageRef];
    CGImageRelease(subImageRef);
    UIGraphicsEndImageContext();
    _boardView.hidden = NO;
    return smallImage;
}
@end
